<template>
  <div class="sel-path-page-layout hor-layout">
    <!--  左边的列表布局  -->
    <el-card class="project-list-layout">
      <template #header>
        <div class="hor-layout-center-all project-card-title">
          项目文件夹列表
          <div class="project-card-right-buttons">
            <el-button type="primary" size="small" @click="importPathData">导入</el-button>
            <el-button type="info" size="small" @click="exportPathData">导出</el-button>
          </div>
        </div>
      </template>
      <div class="ver-layout-center">
        <el-table
          border
          size="small"
          style="height: 60vh"
          ref="projectTableRef"
          :data="pageData.projectList"
          @current-change="onSelectChange"
        >
          <el-table-column label="#" width="40" fixed="left">
            <template #default="scope">
              <el-radio-group
                :model-value="pageData.selectRow && scope.row.id == pageData.selectRow.id"
              >
                <el-radio :value="true"></el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column
            label="项目文件夹路径"
            prop="path"
            width="220px"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="层级" prop="level" width="50px"></el-table-column>
          <el-table-column
            label="过滤文件夹"
            prop="filter"
            width="90px"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="操作" width="70px" fixed="right">
            <template #default="scope">
              <el-button type="danger" size="small" @click.stop="deleteProjectItem(scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!--  右边表单布局  -->
    <el-card class="page-form-card-layout" center>
      <template #header>
        <div class="hor-layout-side-center">
          <el-button v-show="pageData.projectForm.id" size="small" type="text" style="color: white">
            占位
          </el-button>
          <div class="page-card-title">
            {{ pageData.projectForm.id ? '修改项目文件夹' : '新增项目文件夹' }}
          </div>
          <el-button
            v-show="pageData.projectForm.id"
            size="small"
            type="primary"
            @click="newProjectItem"
          >
            新增
          </el-button>
        </div>
      </template>
      <div class="page-content-layout ver-layout-center">
        <el-form
          ref="projectFormRef"
          :model="pageData.projectForm"
          :rules="pageData.projectFormRule"
          :disabled="pageData.loadingProjectTree"
          label-position="left"
          size="small"
          inline
        >
          <el-form-item
            class="form-item-first-view"
            label="项目所在文件夹"
            prop="path"
            size="small"
          >
            <el-input
              readonly
              placeholder="请选择项目所在文件夹"
              v-model="pageData.projectForm.path"
              @click.stop="selectProjectPath"
            >
              <template #suffix>
                <img
                  style="width: 20px; height: 20px"
                  src="../../../assets/image/sgicon-list.svg"
                />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item class="form-item-second-view" label="项目层级" prop="level" size="small">
            <el-input-number v-model="pageData.projectForm.level" min="1" max="5"></el-input-number>
          </el-form-item>
          <el-form-item class="form-item-second-view" label="过滤文件夹" prop="filter" size="small">
            <el-select
              multiple
              collapse-tags
              placeholder="请选择"
              collapse-tags-tooltip
              v-model="pageData.projectForm.filter"
            >
              <el-option
                v-for="item in pageData.projectForm.filter"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <el-tree
          class="project-tree"
          default-expand-all
          highlight-current
          check-on-click-node
          check-strictly
          node-key="id"
          :data="pageData.treeData"
          :props="pageData.defaultProps"
          v-loading="pageData.loadingProjectTree"
          :filter-node-method="filterNode"
          @check-change="handleCheckChange"
          ref="tree2"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node hor-layout-center">
              <span>{{ node.label }}</span>
              <el-button
                v-if="node.level != 1"
                link
                type="danger"
                size="small"
                icon="delete"
                class="delete-icon-view"
                @click="removeTreeData(node, data)"
              ></el-button>
            </span>
          </template>
        </el-tree>
        <el-button
          size="small"
          class="confirm-btn-view"
          v-if="pageData.projectForm.path"
          :type="pageData.selectRow.id ? 'success' : 'primary'"
          :disabled="pageData.loadingProjectTree"
          @click="confirmSelect"
        >
          保存
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { ElMessageBox, FormInstance } from 'element-plus'
import { managePlugin } from '../../../plugins/managePlugin'
import { onMounted, reactive, ref, watch } from 'vue'
import { convertDataToTreeData } from '../../../utils/project/project_utils'
import { generateId, showToast } from '../../../utils/utils'

const mRouter = useRouter()
const projectFormRef = ref<FormInstance>()
const projectTableRef = ref<null>()

//页面数据
const pageData = reactive({
  projectFormRule: {
    path: [
      {
        required: true,
        message: '请选择项目路径'
      }
    ],
    level: [
      {
        required: true,
        message: '请选择级别'
      }
    ]
  },
  projectForm: {
    path: '',
    level: 2,
    filter: []
  },
  treeData: [],
  projectList: [],
  selectRow: {},
  loadingProjectTree: false //加载项目树
})

//监听projectForm值变化
watch(
  () => [pageData.projectForm.path, pageData.projectForm.level, pageData.projectForm.filter],
  async () => {
    let projectData = {},
      lastDirPath = (pageData.projectForm.path && pageData.projectForm.path.split('/')) || []
    lastDirPath = lastDirPath[lastDirPath.length - 1]
    if (!lastDirPath) {
      pageData.treeData = []
      return
    }
    console.log('lastDirPath', lastDirPath)
    pageData.loadingProjectTree = true
    projectData[lastDirPath] = await managePlugin.loadProjectDirsRender(pageData.projectForm)
    pageData.loadingProjectTree = false
    console.log('projectData===', projectData)
    pageData.treeData = convertDataToTreeData(projectData)
  },
  { deep: true }
)

//导入项目配置数据
const importPathData = async () => {
  await ElMessageBox.confirm(`导入后原有数据会被覆盖？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  let { result, message } = await managePlugin.importManageDataRender({ projectPathStr: true })
  await showToast(message, result ? 'success' : 'error')
  if (result) await refreshProjectList()
}

//导出项目配置数据
const exportPathData = async () => {
  let { result, message } = await managePlugin.exportManageDataRender({ projectPathStr: true })
  await showToast(message, result ? 'success' : 'error')
}

//新增项目路径数据
const newProjectItem = () => {
  let newProjectObj = {
    path: '',
    level: 2,
    filter: []
  }
  if (pageData.selectRow.id) projectTableRef.value.setCurrentRow(newProjectObj)
  pageData.projectForm = newProjectObj
}

//选择项目路径
const selectProjectPath = async () => {
  pageData.projectForm.path = await managePlugin.selectDirPathRender()
}

//表单校验
const verifyProjectForm = async () => {
  return new Promise((resolve) => {
    projectFormRef.value.validate((valid, fields) => {
      resolve(valid)
    })
  })
}

//确定选择
const confirmSelect = async () => {
  if (!(await verifyProjectForm())) return
  if (!pageData.selectRow.id) {
    pageData.projectList.push({ ...pageData.projectForm, id: generateId() })
  }
  await confirmSaveProjectData('保存', false)
  newProjectItem()
}

//移除树数据
const removeTreeData = (node, data) => {
  console.log('removeTreeData', node, data)
  pageData.projectForm.filter.push(data.label)
}

//选择表格数据
const onSelectChange = (data1) => {
  pageData.selectRow = data1
  if (pageData.selectRow) pageData.projectForm = pageData.selectRow
}

//删除项目项
const deleteProjectItem = async (tableItem) => {
  await ElMessageBox.confirm(`确认删除项目路径【${tableItem.path}】？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  if (tableItem.id == (pageData.selectRow && pageData.selectRow.id)) newProjectItem()
  pageData.projectList.splice(
    pageData.projectList.indexOf((item) => item.id == tableItem.id),
    1
  )
  await confirmSaveProjectData('删除', false)
}

//保存项目路径数据
const confirmSaveProjectData = async (flag = '保存', backFlag = true) => {
  if (await managePlugin.saveProjectPathRender(JSON.stringify(pageData.projectList))) {
    await showToast(`${flag}成功！`)
    if (backFlag) await mRouter.replace('/home')
  } else {
    await showToast(`${flag}失败！`, 'error')
  }
}

//刷新项目列表数据
const refreshProjectList = async () => {
  let projectList = await managePlugin.getProjectPathRender()
  pageData.projectList = projectList ? JSON.parse(projectList) : []
}

onMounted(async () => {
  await refreshProjectList()
})
</script>

<style scoped lang="less">
.sel-path-page-layout {
  margin-left: 10px;
  width: calc(100% - 10px);
  height: 75vh;

  /deep/ .page-form-card-layout > .el-card__header {
    padding: 10px;
  }

  /deep/ .project-list-layout > .el-card__header {
    padding: 10px;
  }

  //左侧侧的列表布局
  .project-list-layout {
    position: relative;
    width: 50%;
    margin-right: 15px;

    .project-card-title {
      font-size: 14px;
    }

    .project-card-right-buttons {
      position: absolute;
      right: 20px;
    }

    .confirm-save-project-btn {
      margin-top: 10px;
    }
  }

  //右侧表单布局
  .page-form-card-layout {
    width: 50%;

    .page-card-title {
      font-size: 14px;
    }

    .page-content-layout {
      height: 100%;

      .form-item-first-view {
        width: 100%;
      }

      .form-item-second-view {
        width: 50%;
        margin-right: 0;
      }

      .project-tree {
        width: 100%;
        height: 250px;
        overflow-y: auto;
        border: 1px solid #ededed;

        .custom-tree-node {
          flex: 1;
          display: flex;
          font-size: 14px;
          padding-right: 8px;
        }

        .delete-icon-view {
          margin-left: 10px;
        }
      }

      .confirm-btn-view {
        margin-top: 10px;
      }
    }
  }
}
</style>
